// \u4e00-\u9fa5] 中文验证规则

import WXchekc from 'wechat-validate'


Page({
  behaviors:[WXchekc],
  rules:{
    name:[
      {required:true,message:"业主姓名不能为空"},
      {pattern:/^(?:[\u4e00-\u9fa5·]{2,16})$/,message:"业主姓名只能为中文" }
    ],
    mobile:[
      {required:true,message:"手机号码不能为空"},
      {pattern:/^(?:(?:\+|00)86)?1\d{10}$/,message:"手机号码不符合格式"}
    ],
    idcardBackUrl:[{required:true,message:"身份证背面图片不能为空"}],
    idcardFrontUrl:[{required:true,message:"身份证正面图片不能为空"}]
  },
  data: {
    roomtitle:"",
    name:"",
    gender:"1",
    mobile:"",
    idcardFrontUrl:"",
    idcardBackUrl: "",
    point:"",
    building:"",
    room:""
  },
  onChangess(event){
    this.setData({
      gender:event.detail
    })
  },
  async submitfromfn() {

    const rescheck = this.validate()

    if (!rescheck) return 

    const {roomtitle,__webviewId__,...data} = this.data

    const res  = await wx.myRequest.post("/room",{...data})
    console.log(res);

    // if (!valid) return wx.utils.toast(message)
    wx.utils.toast("请求成功！")
    
    console.log(getCurrentPages());
    wx.navigateBack({delta: 4})
  },
  removePicture(ev) {
    // 移除图片的类型（身份证正面或反面）
    const type = ev.mark?.type
    this.setData({ [type]: '' })
  },
  onLoad(ev){
    if (ev.houseId) {
      // __wxConfig.page['house_pkg/pages/form/index.html'].window.navigationBarTitleText = "修改房屋信息"
      this.getHouseItemInfo(ev.houseId)
      return
    }else{
      this.setData({
        point:ev.point,
        building:ev.building,
        room:ev.room
      })
    }

  },
  // 获取房屋信息
  async getHouseItemInfo(id){
    const res =  await wx.myRequest.get(`/room/${id}`)
    this.setData({
      point:res.data.point,
      name:res.data.name,
      gender:res.data.gender.toString(),
      mobile:res.data.mobile,
      idcardFrontUrl:res.data.idcardFrontUrl,
      idcardBackUrl:res.data.idcardBackUrl,
      building:res.data.building,
      room:res.data.room
    })
  },
  // 上传图片
  async uploadImageFn(ev){
    console.log(ev.mark.uploadtype);
    const uploadtype = ev.mark.uploadtype
    const res =  await wx.chooseMedia({
      count:1,
      mediaType:["image"],
      sizeType:"original",
    })
    console.log(res);
    wx.uploadFile({
      url:wx.myRequest.baseURL + "/upload",
      filePath:res.tempFiles[0].tempFilePath,
      name:"file",
      header:{
        Authorization:`Bearer ${getApp().token}`
      },
      success:(res) =>{
        if ((JSON.parse(res.data).code) !== 10000) {
          return wx.utils.toast("请求失败")
        } 
        this.setData({
            [uploadtype]:JSON.parse(res.data).data.url
        })
      }
    })

 


  }
})
